package com.pactera.asmp.server.config;

import com.pactera.asmp.server.common.constants.Constants;
import com.pactera.asmp.server.common.websocket.config.ServerConfig;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Bean
    public RabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }

    @Bean
    public Queue directQueue(ServerConfig serverConfig) {
        // durable:是否持久化,默认是false,持久化队列：会被存储在磁盘上，当消息代理重启时仍然存在，暂存队列：当前连接有效
        // exclusive:默认也是false，只能被当前创建的连接使用，而且当连接关闭后队列即被删除。此参考优先级高于durable
        // autoDelete:是否自动删除，当没有生产者或者消费者使用此队列，该队列会自动删除。

        //一般设置一下队列的持久化就好,其余两个就是默认false

        return new Queue(serverConfig.getUrl(),true);
    }

    //Direct交换机 起名：TestDirectExchange
    @Bean
    DirectExchange directExchange() {
        return new DirectExchange("WsDirectExchange",true,false);
    }
    //绑定  将队列和交换机绑定, 并设置用于匹配键：TestDirectRouting
    @Bean
    Binding bindingDirect(ServerConfig serverConfig) {
        return BindingBuilder.bind(directQueue(serverConfig)).to(directExchange()).with(serverConfig.getUrl());
    }

    @Bean
    DirectExchange commonDirectExchange() {
        return new DirectExchange(Constants.COMMON_DIRECT_EXCHANGE, Boolean.TRUE, Boolean.FALSE);
    }

    @Bean
    public Queue pluginConfigDirectQueue() {
        return new Queue(Constants.PLUGIN_CONFIG_QUEUE, Boolean.TRUE);
    }

    @Bean
    public Queue pluginConfigApkDirectQueue() {
        return new Queue(Constants.PLUGIN_CONFIG_APK_RESULT_QUEUE, Boolean.TRUE);
    }

    @Bean
    Binding bindingPluginConfig() {
        return BindingBuilder.bind(pluginConfigDirectQueue())
                .to(commonDirectExchange()).with(Constants.PLUGIN_CONFIG_ROUTINGKEY);
    }
}